/*
 * InitApp.java
 *
 * Created on March 29, 2007, 8:16 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package listeners;

import helpers.CatalogHelper;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

/**
 *
 * @author Alirio
 */
public class InitApp implements javax.servlet.ServletContextListener {
  
  private static ServletContext ctx;
  
  /** Creates a new instance of InitApp */
  public InitApp() {
  }

  public void contextInitialized(ServletContextEvent servletContextEvent) {
    String driver = servletContextEvent.getServletContext().getInitParameter("driver");
    String url = servletContextEvent.getServletContext().getInitParameter("url");
    String user = servletContextEvent.getServletContext().getInitParameter("user");
    String password = servletContextEvent.getServletContext().getInitParameter("password");
    try {
      Class.forName(driver);
      try {
        java.sql.Connection cnn = java.sql.DriverManager.getConnection(url, user, password);
        servletContextEvent.getServletContext().setAttribute("cnn", cnn);
         
        ctx = servletContextEvent.getServletContext();
        servletContextEvent.getServletContext().setAttribute("ctx", ctx);
        CatalogHelper.createCatalog(servletContextEvent.getServletContext());
      
      } catch (SQLException ex) {
        ex.printStackTrace();
      }
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
    
  }

  public void contextDestroyed(ServletContextEvent servletContextEvent) {
    try {
      ((java.sql.Connection)servletContextEvent.getServletContext().getAttribute("cnn")).close();
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }
  
  public static ServletContext getServletContext() {
    return ctx;
  }
}
